import { Button, Card, Form, Icon, Input, Upload, Select, Radio } from 'antd';
import React, { Component } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { connect } from 'dva';
import { Link, router } from 'umi';
import { formItemLayout } from '@/common/layout/form';
import { singlePageFormLayout } from '../../../../common/layout/form';
import { StoreState } from '@/common/store/store';
import { ProductCategory } from '../../../../models/productCategory';

const FormItem = Form.Item;
const { Option } = Select;

interface FormBasicFormProps extends FormComponentProps {
  categories: ProductCategory[];
  category?: ProductCategory;
  loading?: boolean;
  dispatch: Dispatch<any>;
}

class FormBasicForm extends Component<FormBasicFormProps> {
  handleSubmit = (e: React.FormEvent) => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'productAndFormBasicForm/submitRegularForm',
          payload: values,
        });
      }
    });
  };

  normFile = (e: { fileList: any }) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  onSubmit = () => {
    const { form, dispatch, category } = this.props;
    const { validateFields } = form;
    validateFields((err: any, values: any) => {
      if (!err && dispatch) {
        if (category) {
          dispatch({
            type: 'productCategory/update',
            payload: {
              ...category,
              ...values,
            },
            callback: () => {
              router.push({
                pathname: '/product/category',
              });
            },
          });
        } else {
          dispatch({
            type: 'productCategory/add',
            payload: values,
            callback: () => {
              router.push({
                pathname: '/product/category',
              });
            },
          });
        }
      }
    });
  };

  reset = () => {
    this.props.form.resetFields();
  };

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      categories,
      category,
    } = this.props;

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const categoryOptions = categories
      .filter(item => item.level === 1)
      .map(item => (
        <Option key={item.id} value={item.id}>
          {item.name}
        </Option>
      ));

    return (
      <Card
        title={
          <div>
            <Icon type="plus-square" />
            <span style={{ marginLeft: '5px' }}>添加分类</span>
          </div>
        }
        extra={
          <Link to="/product/category">
            <Button>返回</Button>
          </Link>
        }
        style={{
          maxWidth: '750px',
          margin: 'auto',
        }}
        bordered
      >
        <Form layout="horizontal" style={singlePageFormLayout} onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label="分类名称">
            {getFieldDecorator('name', {
              initialValue: category?.name,
              rules: [
                {
                  required: true,
                  message: '请输入品牌名称',
                },
              ],
            })(<Input />)}
          </FormItem>
          <FormItem {...formItemLayout} label="上级分类">
            {getFieldDecorator('parentId', {
              initialValue: category?.parentId || 0,
            })(
              <Select disabled={category !== undefined}>
                <Option value={0}>无上级分类</Option>
                {categoryOptions}
              </Select>,
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="数量单位">
            {getFieldDecorator('productUnit', {
              initialValue: category?.productUnit,
            })(<Input />)}
          </FormItem>
          <FormItem {...formItemLayout} label="排序">
            {getFieldDecorator('sort', {
              initialValue: category?.sort || 0,
            })(<Input />)}
          </FormItem>
          {/* <Form.Item {...formItemLayout} label="是否显示">
            {getFieldDecorator('showStatus', {
              initialValue: 0,
            })(
              <Radio.Group>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>,
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="显示在导航栏">
            {getFieldDecorator('navStatus', {
              initialValue: 0,
            })(
              <Radio.Group>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>,
            )}
          </Form.Item> */}
          <FormItem {...formItemLayout} label="分类图标" help="请选择一张图片作为分类图标">
            {getFieldDecorator('icon', {
              valuePropName: 'fileList',
              getValueFromEvent: this.normFile,
            })(
              <Upload name="logo" listType="picture">
                <Button type="primary" disabled={category !== undefined}>
                  点击上传
                </Button>
              </Upload>,
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label="关键词">
            {getFieldDecorator('keywords')(<Input />)}
          </FormItem>
          <FormItem {...formItemLayout} label="描述">
            {getFieldDecorator('description')(<TextArea />)}
          </FormItem> */}
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" onClick={this.onSubmit} loading={loading}>
              提交
            </Button>
            <Button onClick={this.reset} style={{ marginLeft: 8 }}>
              重置
            </Button>
          </FormItem>
        </Form>
      </Card>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  categories: state.productCategory.categories,
  category: state.productCategory.category,
  loading: state.loading.models.productCategory,
});

export default Form.create<FormBasicFormProps>()(connect(mapStateToProps)(FormBasicForm));
